import sys
import os
import tempfile
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QLineEdit, QMessageBox, QHBoxLayout
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEngineProfile, QWebEnginePage
from PyQt5.QtCore import QUrl

class BrowserWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('网页HTML爬取浏览器')
        self.setGeometry(100, 100, 800, 600)

        layout = QVBoxLayout()

        self.url_input = QLineEdit('https://www.example.com')
        self.load_button = QPushButton('加载URL')
        self.load_button.clicked.connect(self.load_new_url)

        url_layout = QHBoxLayout()
        url_layout.addWidget(self.url_input)
        url_layout.addWidget(self.load_button)
        layout.addLayout(url_layout)

        # 创建临时目录用于存储浏览器配置
        self.temp_dir = tempfile.mkdtemp()
        self.profile = QWebEngineProfile(self.temp_dir)

        self.browser = QWebEngineView()
        self.browser.setPage(QWebEnginePage(self.profile))
        layout.addWidget(self.browser)

        self.scrape_button = QPushButton('爬取当前页面并保存在当前目录')
        self.scrape_button.clicked.connect(self.scrape_current_page)
        self.scrape_button.setEnabled(False)  # 初始时禁用爬取按钮
        layout.addWidget(self.scrape_button)

        self.setLayout(layout)

        # 连接页面加载完成信号
        self.browser.loadFinished.connect(self.on_load_finished)

    def load_new_url(self):
        url = QUrl(self.url_input.text())
        self.browser.setUrl(url)

    def on_load_finished(self, ok):
        if ok:
            self.scrape_button.setEnabled(True)  # 页面加载完成后启用爬取按钮
            QMessageBox.information(self, "信息", "页面已加载完成。")

    def scrape_current_page(self):
        def handle_html(html_str):
            if html_str:
                with open('output.html', 'w', encoding='utf-8') as file:
                    file.write(html_str)
                QMessageBox.information(self, "信息", "HTML内容已保存到output.html文件中。")

        self.browser.page().toHtml(handle_html)

    def closeEvent(self, event):
        # 在窗口关闭时删除临时目录
        import shutil
        shutil.rmtree(self.temp_dir, ignore_errors=True)
        super().closeEvent(event)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = BrowserWindow()
    ex.show()
    sys.exit(app.exec_())